package com.mazaiting.imqq.presenter.message;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.Toast;
import cn.bmob.newim.bean.BmobIMMessage;
import cn.bmob.newim.bean.BmobIMMessageType;
import cn.bmob.newim.bean.BmobIMUserInfo;
import cn.bmob.newim.event.MessageEvent;
import cn.bmob.newim.event.OfflineMessageEvent;
import cn.bmob.newim.listener.BmobIMMessageHandler;
import cn.bmob.newim.notification.BmobNotificationManager;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;
import com.mazaiting.imqq.R;
import com.mazaiting.imqq.model.db.manager.NewFriendManager;
import com.mazaiting.imqq.model.message.AddFriendMessage;
import com.mazaiting.imqq.model.message.AgreeAddFriendMessage;
import com.mazaiting.imqq.model.bean.NewFriend;
import com.mazaiting.imqq.model.bean.UserInfo;
import com.mazaiting.imqq.presenter.listener.UpdateCacheListener;
import com.mazaiting.imqq.presenter.user.UserManager;
import com.mazaiting.imqq.ui.activity.MainActivity;
import com.mazaiting.imqq.ui.event.MainContactsEvent;
import com.mazaiting.imqq.ui.event.MainMessageEvent;
import com.mazaiting.imqq.ui.event.MainRefreshEvent;
import com.orhanobut.logger.Logger;
import java.util.List;
import java.util.Map;
import org.greenrobot.eventbus.EventBus;

/**
 * 自定义消息接收器处理在线消息和离线消息
 * Created by mazaiting on 2017/9/4.
 */

public class MessageHandler extends BmobIMMessageHandler {
  private Context mContext;
  public MessageHandler(Context context) {
    this.mContext = context;
  }

  @Override public void onMessageReceive(MessageEvent messageEvent) {
    Toast.makeText(mContext, "在线消息", Toast.LENGTH_SHORT).show();
    // 在线消息
    //Logger.e(messageEvent.getMessage().toString());
    //当接收到服务器发来的消息时，此方法被调用
    executeMessage(messageEvent);
  }

  @Override public void onOfflineReceive(OfflineMessageEvent offlineMessageEvent) {
    Toast.makeText(mContext, "离线消息", Toast.LENGTH_SHORT).show();
    // 离线消息
    // 每次调用connect方法时会查询一次离线消息，如果有，此方法会被调用
    Map<String, List<MessageEvent>> eventMap = offlineMessageEvent.getEventMap();
    Logger.e("有 " + eventMap.size() + " 个用户发来离线消息");
    // 挨个检测下离线消息所属的用户的信息是否需要更新
    for (Map.Entry<String, List<MessageEvent>> entry : eventMap.entrySet()){
      List<MessageEvent> list = entry.getValue();
      int size = list.size();
      Logger.e("用户 " + entry.getKey() + "发来" + size + "条消息");
      for (int i=0;i<size;i++){
        // 处理每条消息
        executeMessage(list.get(i));
      }
    }
  }

  /**
   * 执行在线消息处理
   * @param messageEvent
   */
  private void executeMessage(final MessageEvent messageEvent) {
    Toast.makeText(mContext, "执行消息", Toast.LENGTH_SHORT).show();
    UserManager.getInstance().updateUserInfo(messageEvent, new UpdateCacheListener() {
      @Override public void done(BmobException e) {
        BmobIMMessage message = messageEvent.getMessage();
        Logger.e(message.getMsgType());
        if (BmobIMMessageType.getMessageTypeValue(message.getMsgType()) == 0){
          // 自定义的消息类型： 0
          processCustomMessage(message, messageEvent.getFromUserInfo());
        } else {
          // SDK内部支持的消息类型
          processSDKMessage(message, messageEvent);
        }
      }
    });
  }

  /**
   * SDK内部支持的消息类型
   * @param message
   * @param messageEvent
   */
  private void processSDKMessage(BmobIMMessage message, MessageEvent messageEvent) {
    Toast.makeText(mContext, "内部消息", Toast.LENGTH_SHORT).show();
    if (BmobNotificationManager.getInstance(mContext).isShowNotification()){
      // 如果需要显示通知栏,SDK提供以下两种显示方式：
      Intent pendingIntent = new Intent(mContext, MainActivity.class);
      pendingIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);

      // 8.5 多个用户的多条消息合并成一条通知：有XX个联系人发来了XX条消息
      // BmobNotificationManager.getInstance(context).showNotification(event, pendingIntent);
      // 8.6 自定义通知消息：始终只有一条通知，新消息覆盖旧消息
      BmobIMUserInfo info = messageEvent.getFromUserInfo();
      // 这里是应用图标， 也可以将聊天头像转换成bitmap
      Bitmap bitmap = BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.ic_launcher);
      BmobNotificationManager.getInstance(mContext).showNotification(bitmap,
          info.getName(), message.getContent(), "您有一条新消息", pendingIntent);
    } else {
      // 直接发送消息事件
      EventBus.getDefault().post(new MainMessageEvent());
    }

  }

  /**
   * 自定义的消息类型： 0
   * @param message
   * @param info
   */
  private void processCustomMessage(BmobIMMessage message, BmobIMUserInfo info) {
    Toast.makeText(mContext, "自定义消息", Toast.LENGTH_SHORT).show();
    // 消息类型
    String msgType = message.getMsgType();
    Logger.e(msgType);
    //// 发送页面刷新的广播
    //EventBus.getDefault().post(new MainRefreshEvent());
    // 处理消息
    if (msgType.equals(AddFriendMessage.ADD)) {// 接收到添加好友的请求
      NewFriend newFriend = AddFriendMessage.convert(message);
      EventBus.getDefault().post(new MainContactsEvent());
      // 本地校验
      long id = (NewFriendManager.getInstance(mContext)).insertOrUpdateNewFriend(newFriend);
      if (id > 0){
        showAddNotify(newFriend);
      }
    } else if (msgType.equals(AgreeAddFriendMessage.AGREE)){// 接收到的对方同意添加自己为好友,此时需要做的事情：1、添加对方为好友，2、显示通知
      AgreeAddFriendMessage addFriendMessage = AgreeAddFriendMessage.convert(message);
      addFriend(addFriendMessage.getFromId());// 添加消息的发送方为好友
      EventBus.getDefault().post(new MainRefreshEvent());
      // 本地校验
      showAgreeNotify(info, addFriendMessage);
    } else {
      Toast.makeText(mContext, "接收到的自定义消息：" + message.getMsgType() + "," + message.getContent() + "," + message.getExtra(), Toast.LENGTH_SHORT).show();
    }

  }

  /**
   * 显示同意的通知
   * @param info
   * @param addFriendMessage
   */
  private void showAgreeNotify(BmobIMUserInfo info, AgreeAddFriendMessage addFriendMessage) {
    Intent pendingIntent = new Intent(mContext, MainActivity.class);
    pendingIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
    Bitmap largeIcon = BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.ic_launcher);
    BmobNotificationManager.getInstance(mContext).showNotification(largeIcon, info.getName(),
        addFriendMessage.getMsg(), addFriendMessage.getMsg(), pendingIntent);
  }

  /**
   * 好友管理：收到同意添加好友后添加好友
   * @param fromId
   */
  private void addFriend(String fromId) {
    UserInfo userInfo = new UserInfo();
    userInfo.setObjectId(fromId);
    UserManager.getInstance().agreeAddFriend(userInfo, new SaveListener<String>() {
      @Override public void done(String s, BmobException e) {
        if (e == null){
          Logger.e("success");
        } else {
          Logger.e(e.getMessage());
        }
      }
    });
  }

  /**
   * 有好友请求，通知用户
   * @param newFriend
   */
  private void showAddNotify(NewFriend newFriend) {
    Intent pendingIntent = new Intent(mContext, MainActivity.class);
    pendingIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
    // 这里可以是应用图标，也可以将聊天头像转成bitmap
    Bitmap bitmap = BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.ic_launcher);
    BmobNotificationManager.getInstance(mContext).showNotification(bitmap,
        newFriend.getName(), newFriend.getMsg(), newFriend.getName()+"请求添加你为朋友",
          pendingIntent);
  }
}
